package io.github.kimmking.jvmstudy.jmx;

import javax.management.*;
import javax.management.remote.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Iterator;
import java.util.Set;

public class UserJmxClient {
    public static void main(String[] args){
        try {

            String surl = "service:jmx:rmi:///jndi/rmi://localhost:1099/user";
            JMXServiceURL url = new JMXServiceURL(surl);
            JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
            MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

            System.out.println("Domains:---------------");
            String domains[] = mbsc.getDomains();
            for (int i = 0; i < domains.length; i++) {
                System.out.println("\tDomain[" + i + "] = " + domains[i]);
            }
            System.out.println("all ObjectName：---------------");
            Set<ObjectInstance> set = mbsc.queryMBeans(null, null);
            for (Iterator<ObjectInstance> it = set.iterator(); it.hasNext();) {
                ObjectInstance objectInstance = (ObjectInstance) it.next();
                System.out.println("\t" + objectInstance.getObjectName() + " => " + objectInstance.getClassName());
            }
            System.out.println("user:name=User：---------------");
            ObjectName mbeanName = new ObjectName("user:name=User");
            MBeanInfo info = mbsc.getMBeanInfo(mbeanName);
            System.out.println("Class: " + info.getClassName());
            if (info.getAttributes().length > 0){
                for(MBeanAttributeInfo m : info.getAttributes())
                    System.out.println("\t ==> Attriber：" + m.getName());
            }
            if (info.getOperations().length > 0){
                for(MBeanOperationInfo m : info.getOperations())
                    System.out.println("\t ==> Operation：" + m.getName());
            }

            System.out.println("Testing userName and userId .......");
            Object userNameObj = mbsc.getAttribute(mbeanName,"UserName");
            System.out.println("\t ==> userName：" + userNameObj);
            Object userIdObj = mbsc.getAttribute(mbeanName,"UserId");
            System.out.println("\t ==> userId：" + userIdObj);

            Attribute userNameAttr = new Attribute("UserName","kimmking");
            mbsc.setAttribute(mbeanName,userNameAttr);

            System.out.println("Modify UserName  .......");

            userNameObj = mbsc.getAttribute(mbeanName,"UserName");
            System.out.println("\t ==> userName：" + userNameObj);

            jmxc.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}
